/**
 * @title 非标信息维护
 */
import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Spin } from 'antd';
import moment from 'moment';

import { connect } from 'dva';
import { AdvancedSearch, DATA_ENTRY, ModalC, PrimaryC, TableC, ExportC } from '../../../../comps';
//组件
import RightInfo from '../shareComp/rightInfo';
import TipsInfo from '../shareComp/tipInfo';
import MyModal from './myModal';

import _ from 'lodash';
import myStyle from '../index.less';
import { findTitleByValue, findValueByCode } from '../../../../utils/utils';

@Form.create()
@connect(({ loading, userM: user, globalM, bondInformationM }) => ({
  user,
  batchConfirmLoading: loading.effects['manNonStandardMaintenanceM/batchConfirm'],
  addLoading: loading.effects['manNonStandardMaintenanceM/nonStandardMaintenanceAdd'],
  tableLoading: loading.effects['manNonStandardMaintenanceM/getDataList'],
  globalM,
  bondInformationM,
  loading,
}))
export default class nonStandardMaintenance extends PureComponent {
  state = {
    columns: [
      { title: '证券代码', key: 'tradingCode' },
      {
        title: '证券名称',
        key: 'tradingName',
      },
      { title: '资产类别', key: 'assetType' },
      { title: '收/受益权类型', key: 'jgbb_ssyqlx' },
      { title: '投向部分分类', key: 'jgbb_txbffl' },
      { title: '租户', key: 'tenant' },
    ],
    dataSource: [],
    pageInfo: {
      // 分页页码
      currentPage: 1,
      numInPage: 10,
    },
    count: 0, //与资讯不一致的条数
    searchData: {}, // 查询条件
    isReset: false,
    selectedRowKeys: [],
    selectedRows: [],
    assetTypeList: [
      { value: '2', title: '收/受益权' },
      { value: '9', title: '其他' },
    ],
    editRow: undefined,
    addVisible: false,
    flag: '1', //1全部 2不一致 3无评级
    addedThisMonth: 0, //本月新增条数
    isHistory: false, //是否是历史日期
    holdDataList: [], //持仓日期下拉
    latestholdDate: '', //最新的持仓日期
  };
  componentDidMount() {
    this.props.onRef && this.props.onRef(this);

    //查询持仓日期
    this.props.dispatch({
      type: 'bondInformationM/queryHoldDataList',
      payload: {},
      callback: (data) => {
        if (data) {
          let temp = [];
          data.map((item) => {
            temp.push({
              value: item,
              title: item,
            });
          });
          //设置默认值为最新的持仓日期 其余下拉日期为历史日期
          this.AdvancedSearchRef?.props.form?.setFieldsValue({
            holdDate: data.length ? data[0] : undefined,
          });
          let obj = this.state.searchData;
          obj.holdDate = data.length ? data[0] : undefined;
          this.setState(
            {
              holdDataList: [...temp],
              searchData: { ...obj },
              latestholdDate: data.length ? data[0] : undefined, ////保存最新的持仓
              tenant: this.props.tenant,
            },
            () => {
              this.getTableData();
            },
          );
        } else {
          this.setState({ holdDataList: [] });
        }
      },
    });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (nextProps.tenant != this.props.tenant) {
      this.setState(
        {
          tenant: nextProps.tenant,
        },
        () => {
          this.getTableData();
        },
      );
    }
  }
  //查询
  onQuery = (_data) => {
    const {
      pageInfo: { numInPage },
    } = this.state;
    //如果子查询还在 不可以点击查询按钮
    if (this.state.flag != '1') {
      message.warning('请点击与资讯不一致提示语句，取消查询后重试！');
      return;
    }
    // 判断是历史数据还是当前数据
    if (this.AdvancedSearchRef) {
      if (this.state.latestholdDate != this.AdvancedSearchRef.props.form.getFieldValue('holdDate')) {
        this.setState({
          flag: '1', //历史数据 永远查询全部
        });
      }
      this.setState({
        isHistory: this.state.latestholdDate == this.AdvancedSearchRef.props.form.getFieldValue('holdDate') ? false : true,
      });
    }
    this.setState(
      {
        pageInfo: {
          currentPage: 1,
          numInPage,
        },
        isReset: false,
        searchData: _data,
      },
      () => {
        this.getTableData();
      },
    );
  };
  //重置
  onClear = () => {
    this.setState({
      isReset: true,
    });
    //重置日期
    this.AdvancedSearchRef?.props.form?.setFieldsValue({
      holdDate: this.state.latestholdDate,
    });
    //租户也重置
    this.props.resetTenant();
  };
  // 查询条件
  renderForm = () => {
    const searchProps = {
      onRef: (ref) => (this.nonStandardSearchRef = ref),
      onQuery: this.onQuery,
      onClear: this.onClear,
      dataSource: [
        {
          dataIndex: 'codeName',
          type: DATA_ENTRY.INPUT,
          title: '代码或名称',
        },
        {
          dataIndex: 'isConfirm',
          type: DATA_ENTRY.SELECT,
          isTrueFalseJudge: true,
          allowClear: true,
          showSearch: false,
          title: '是否已确认',
        },
        {
          dataIndex: 'holdDate',
          title: '持仓日期',
          type: DATA_ENTRY.SELECT,
          allowClear: false,
          dataSource: this.state.holdDataList || [],
        },
      ],
      onRef: (ref) => (this.AdvancedSearchRef = ref),
    };
    return <AdvancedSearch {...searchProps} />;
  };
  // 获取表格数据
  getTableData = () => {
    const that = this;
    const {
      searchData,
      pageInfo: { currentPage, numInPage },
    } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'manNonStandardMaintenanceM/getDataList',
      payload: {
        ...searchData,
        currentPage,
        numInPage,
        flag: this.state.flag,
        tenant: this.state.tenant, //点击跳转页 就是查询原租
      },
      callback: (msg, _data) => {
        if (msg == 'success') {
          that.setState({
            dataSource: _data.dataSource,
            pageInfo: _data.pageInfo,
            count: _data.count || 0,
            addedThisMonth: _data.addedThisMonth || 0,
            selectedRowKeys: [],
            selectedRows: [],
          });
        } else {
          that.setState({
            dataSource: [],
            pageInfo: {},
            count: 0,
            addedThisMonth: 0,
            selectedRowKeys: [],
            selectedRows: [],
          });
        }
      },
    });
  };
  // 批量确认
  confirm = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    const { dispatch } = this.props;
    //点击批量确认的时候，前端需要判断有几条数据待补充，并且做出提示
    let selectLength = selectedRows.filter((item) => item.isSuppleInfo == '1')?.length;
    if (selectLength) {
      message.warning(`您有${selectLength}条信息待补充`);
      return false;
    }
    dispatch({
      type: 'manNonStandardMaintenanceM/batchConfirm',
      payload: {
        data: selectedRowKeys,
      },
      callback: (res) => {
        if (res === 'success') {
          this.getTableData();
        }
      },
    });
  };
  //表格分页切换
  handleTableChange = (pagination) => {
    const { current, pageSize } = pagination;
    const { isReset } = this.state;
    if (isReset) {
      //判断是否点击了重置 点击页码不进行后台查询
      message.warning('查询条件已被重置，请重新查询。');
      return;
    }
    this.setState(
      {
        pageInfo: {
          currentPage: current,
          numInPage: pageSize,
        },
      },
      () => {
        this.getTableData();
      },
    );
  };
  // 新增/编辑 初始化数据
  editRow = (record = undefined) => {
    this.setState({
      editRow: record,
      addVisible: true,
    });
  };
  // 新增/编辑 确认
  addOnOk = () => {
    const that = this;
    const { dispatch } = this.props;
    let params = this.myModalRef?.getInfo();
    if (params)
      // 发请求
      dispatch({
        type: 'manNonStandardMaintenanceM/nonStandardMaintenanceAdd',
        payload: {
          ...params,
        },
        callback: (msg) => {
          if (msg == 'success') {
            that.getTableData();
            this.onCancel(); //关闭模态框
          }
        },
      });
  };
  //关闭模态框
  onCancel = () => {
    this.setState(
      {
        addVisible: false,
        editRow: undefined,
      },
      () => {
        //清空表单
        setTimeout(() => {
          this.myModalRef.reset();
        }, 300);
      },
    );
  };

  // 新增模态框
  renderModal = () => {
    const { addVisible, editRow } = this.state;
    const { addLoading } = this.props;
    const modalProps = {
      title: editRow ? '编辑' : '新增',
      visible: addVisible,
      cancelButtonProps: {
        loading: addLoading,
      },
      confirmLoading: addLoading || this.props.loading.effects['manNonStandardMaintenanceM/backfillDetail'] === true,
      maskClosable: false,
      destroyOnClose: false,
      width: 800,
      onCancel: this.onCancel,
      onOk: this.addOnOk,
    };
    return (
      <ModalC {...modalProps}>
        <MyModal editRow={editRow} onRef={(ref) => (this.myModalRef = ref)} />
      </ModalC>
    );
  };
  //点击了提示语
  tipClick = (flag) => {
    this.setState(
      {
        flag: flag == true ? '2' : '1',
      },
      () => {
        this.setState(
          {
            isReset: false, // 是否点击重置
            selectedRowKeys: [], // 表格checkbox选择
            selectedRows: [], // 表格checkbox选择
            isBatchConfirmation: false, // 批量确认按钮置灰
            currentPage: 1,
          },
          () => {
            this.getTableData();
          },
        );
      },
    );
  };
  // 表格渲染
  renderTable = () => {
    const {
      searchData,
      dataSource,
      columns,
      pageInfo: { numInPage, currentPage, total },
      selectedRowKeys,
      assetTypeList,
      count = 0,
    } = this.state;
    const {
      batchConfirmLoading,
      globalM: {
        dataDictionary: { ASSETS_TXBFFL = [], NONSTANDAR_JGBB_SSYQLX1 = [] },
      },
      tableLoading,
    } = this.props;
    let newColumns = _.cloneDeep(columns);
    if (newColumns?.length > 0) {
      newColumns.forEach((item) => {
        if (item.key === 'assetType') {
          item.render = (text, record) => {
            if (!text) {
              return '--';
            }
            return findTitleByValue(text, assetTypeList);
          };
        }
        if (item.key === 'jgbb_txbffl') {
          item.render = (text, record) => {
            if (!text) {
              return '--';
            }
            return findValueByCode(text, ASSETS_TXBFFL);
          };
        }
        if (item.key === 'jgbb_ssyqlx') {
          item.render = (text, record) => {
            if (!text) {
              return '--';
            }
            return findValueByCode(text, NONSTANDAR_JGBB_SSYQLX1);
          };
        }
      });
      !this.state.isHistory &&
        newColumns.push({
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          type: 'operate',
          fixed: 'right',
          operates: [
            {
              title: '编辑',
              onClick: (record, index) => {
                this.editRow(record);
              },
            },
          ],
        });
    }
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRowKeys,
          selectedRows,
        });
      },
      getCheckboxProps: (record) => ({
        disabled: record.isConfirm == '1' || record.isSuppleInfo == '1', // 列是否可选
      }),
      selectedRowKeys: selectedRowKeys,
    };
    return (
      <>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '20px' }}>
          <div style={{ display: 'flex', alignContent: 'center' }}>
            {!this.state.isHistory && (
              <div>
                <PrimaryC
                  title='新增'
                  onClick={() => {
                    this.editRow();
                  }}
                ></PrimaryC>
              </div>
            )}
            {!this.state.isHistory && (
              <div style={{ marginLeft: '16px', marginRight: '20px' }}>
                <PrimaryC
                  title='批量确认'
                  onClick={() => {
                    this.confirm();
                  }}
                  loading={batchConfirmLoading}
                  disabled={!selectedRowKeys?.length}
                ></PrimaryC>
              </div>
            )}
            <div style={{ marginRight: '20px' }}>
              <ExportC
                url={'gateway/instrument-server/regulationInfo/nonStandardExport'}
                search={{ ...searchData, flag: this.state.flag, tenant: this.state.tenant }}
                disabled={dataSource?.length ? false : true}
              />
            </div>
            {!this.state.isHistory && (
              <div style={{ display: 'flex' }}>
                <TipsInfo count={count} handleClick={this.tipClick}></TipsInfo>
              </div>
            )}
          </div>
          {!this.state.isHistory && (
            <div style={{ display: 'flex' }}>
              <RightInfo redTitle={`本月新增标的${this.state.addedThisMonth || 0}只`}></RightInfo>
            </div>
          )}
        </div>
        <div style={{ marginTop: '16px' }}>
          <TableC
            columns={newColumns}
            loading={tableLoading}
            dataSource={dataSource}
            current={currentPage}
            total={total}
            pageSize={numInPage}
            rowKey='id'
            scroll={{ x: 'max-content' }}
            onChange={this.handleTableChange}
            rowSelection={!this.state.isHistory ? rowSelection : undefined}
            rowClassName={(record) => {
              return record.createTs == this.state.latestholdDate ? myStyle.redCls : '';
            }}
          />
        </div>
      </>
    );
  };
  render() {
    return (
      <div>
        {this.renderForm()}
        {this.renderTable()}
        {this.renderModal()}
      </div>
    );
  }
}
